package com.fjw.realm;


import com.fjw.pojo.SysUser;
import com.fjw.service.PermsService;
import com.fjw.service.RoleService;
import com.fjw.service.SysUserService;
import lombok.Data;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

@Data
public class Myrealm extends AuthorizingRealm {

    //注入service 在工厂中注入
    private SysUserService sysUserService;
    private RoleService roleService;
    private PermsService permsService;
    //判断是否支持token


    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof UsernamePasswordToken){
            return true;
        }
        return false;
    }


    /**
     * 验证权限和角色 时执行
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        //在工厂中注入service


        //从另一个项目执行方法
//        try {
//            Set<String> permission = (Set<String>) Request.Get("http://ssx:8082/cxf/ssx/findPermissionByUserName")
//                    .bodyByteArray(username.getBytes())
//                    .execute()
//                    .returnContent();
//            Set<String> role = (Set<String>) Request.Get("http://ssx:8082/cxf/ssx/findRoleByUserName")
//                    .bodyByteArray(username.getBytes())
//                    .execute()
//                    .returnContent();

        Set<String> role = roleService.findAllRole(username);
        Set<String> permission = permsService.findAllPerms(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(role);
        simpleAuthorizationInfo.setStringPermissions(permission);
        return simpleAuthorizationInfo;
//            } catch (IOException e) {
//                e.printStackTrace();
//                throw new RuntimeException("从另一个服务器取数据失败" ,e);
//            }


    }

    /**
     * 身份凭证验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.从token中过去用户输入的信息
        String username = (String) token.getPrincipal();
        //2.通过username去数据库查询
        SysUser sysUser = sysUserService.queryByUsername(username);
        //3.判断下user是否为空 如果为空返回null 交给后面的组件进行抛出异常
        if (sysUser==null){
            return null;
        }
        //4.封装成AuthenticationInfo的一个子类 用户名 密码 盐 getName 后面交给密码比对器判断
        return new SimpleAuthenticationInfo(sysUser.getUsername(),sysUser.getPassword(),getName());
    }
}
